﻿using System;
using System.IO;
using word = Microsoft.Office.Interop.Word;

namespace IceDog.DNF.Program.UnitTest.Helpers
{
    /// <summary>
    /// Microsoft Office Interop（MOI）交互帮助类
    /// </summary>
    public static class MOIHelper
    {
        private static word.ApplicationClass _wordApp = null;

        /// <summary>
        /// 表示缺失的值，一个编程时需要经常使用的一个参数
        /// </summary>
        public static object MissingValue = System.Reflection.Missing.Value;

        /// <summary>
        /// 获取 word 段落
        /// </summary>
        /// <param name="doc">文档对象</param>
        /// <param name="index">段落索引</param>
        /// <returns></returns>
        public static string GetParagraph(word.Document doc, int index)
        {
            //这是一个设定对应的某一段
            word.Paragraph p = doc.Content.Paragraphs[index];
            return p.Range.Text;
        }

        /// <summary>
        /// 将doc某一段的内容复制到剪贴板上
        /// </summary>
        /// <param name="doc">文档对象</param>
        /// <param name="index">段落索引</param>
        /// <returns></returns>
        public static void CopyParagraph(word.Document doc, int index)
        {
            //这是一个设定对应的某一段
            word.Paragraph p = doc.Content.Paragraphs[index];
            p.Range.Copy();
        }

        /// <summary>
        /// 将doc某一段包含表格的内容复制到剪贴板上
        /// </summary>
        /// <param name="doc">文档对象</param>
        /// <param name="startIndex">开始的段落索引</param>
        /// <param name="endIndex">结束的段落索引</param>
        /// <returns></returns>
        public static void CopyParagraphContainTable(word.Document doc, int startIndex, int endIndex)
        {
            //在这个复制过程中，重新建立了一个区域 word.Range range = doc.Range(); 这个区域包括文档的所有内容。
            //然后根据段落的要求分别设定区域的Start 和 End ，如果在 Start  和 End 之间有一个表格的话，那么表格也
            //会被正确复制过去.
            word.Range range = doc.Range();

            word.Paragraph para1;
            para1 = doc.Content.Paragraphs[startIndex];
            range.Start = para1.Range.Start;

            word.Paragraph para2;
            para2 = doc.Content.Paragraphs[endIndex];
            range.End = para2.Range.End;

            range.Copy();
        }

        /// <summary>
        /// 将剪贴板的内容粘贴到doc文档中
        /// </summary>
        /// <param name="doc">文档对象</param>
        /// <param name="index">段落索引</param>
        /// <returns></returns>
        public static void PasteParagraph(word.Document doc)
        {
            word.Paragraph p = doc.Content.Paragraphs.Add(ref MissingValue);
            try
            {
                p.Range.Paste();
                p.Range.InsertParagraphBefore();//添加一次回车
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        /// <summary>
        /// 新建word文档
        /// </summary>
        /// <param name="wordApp">word程序</param>
        /// <param name="doc">文档</param>
        public static void CreateWordDoc(word.ApplicationClass wordApp, string docName, bool isActivate = false)
        {
            if (File.Exists(docName))
            {
                throw new Exception("file is exist");
            }
            word.Document doc = GetWordDoc(wordApp,"",false);  //doc对象

            //WdSaveDocument为Word2003文档的保存格式(文档后缀.doc)
            //wdFormatDocumentDefault为Word2007的保存格式(文档后缀.docx)
            object format = word.WdSaveFormat.wdFormatDocument;
            object name = docName;
            doc.SaveAs2(ref name, ref format, ref MissingValue, ref MissingValue, ref MissingValue,
                ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
                ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
                ref MissingValue, ref MissingValue);
            CloseWordDoc(wordApp, doc);
            CloseWordApp(wordApp);
        }

        /// <summary>
        /// 打开word文档
        /// </summary>
        /// <param name="wordApp">word程序</param>
        /// <param name="doc">文档</param>
        public static word.Document GetWordDoc(word.ApplicationClass wordApp, string docName, bool isActivate = false)
        {
            word.Document doc = null;  //doc对象
            object docObject = docName;  //由于COM操作中，都是使用的 object ,所以，需要做一些转变
            if (File.Exists(docName))
            {
                doc = wordApp.Documents.Add(ref docObject, ref MissingValue, ref MissingValue, ref MissingValue);
            }
            else   //如果文件名不存在，就打开一个新的空白文档
            {
                doc = wordApp.Documents.Add(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);
            }
            //将当前文件设定为活动文档
            if (isActivate)
            {
                doc.Activate();
            }
            return doc;
        }

        /// <summary>
        /// 关闭 word文档
        /// </summary>
        /// <param name="wordApp">word程序</param>
        /// <param name="doc">文档</param>
        public static void CloseWordDoc(word.ApplicationClass wordApp, word.Document doc)
        {
            word._Document docc = doc as word._Document;
            docc.Close(ref MissingValue, ref MissingValue, ref MissingValue);
        }

        /// <summary>
        /// 获取 word 程序
        /// </summary>
        public static word.ApplicationClass GetWordApp()
        {
            //保持只有一个对象实例
            if (_wordApp == null)
            {
                _wordApp = new word.ApplicationClass();
            }
            return _wordApp;
        }

        /// <summary>
        /// 关闭 word 程序
        /// </summary>
        /// <param name="wordApp">word程序</param>
        public static void CloseWordApp(word.ApplicationClass wordApp)
        {
            wordApp.Quit(ref MissingValue, ref MissingValue, ref MissingValue);
        }

        /// <summary>
        /// 替换word文档内容
        /// </summary>
        /// <param name="doc">文档对象</param>
        /// <param name="oldContent">要被替换的内容</param>
        /// <param name="newContent">新的内容</param>
        /// <example>
        /// 如果要替换其中的回车符为空格，可以这样使用ReplaceWordDocContent（"^p","");
        /// 这一点，与在WORD中使用的替换功能是一样的。
        /// </example>
        public static void ReplaceWordDocContent(word.Document doc, string oldContent, string newContent)
        {
            doc.Content.Find.Text = oldContent;
            object FindText, ReplaceWith, ReplaceAll;
            FindText = oldContent;
            ReplaceWith = newContent;
            ReplaceAll = word.WdReplace.wdReplaceAll;
            doc.Content.Find.Execute(ref FindText, ref MissingValue, ref MissingValue, ref MissingValue,
                ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
                ref ReplaceWith, ref ReplaceAll, ref MissingValue, ref MissingValue, ref MissingValue,
                ref MissingValue);
        }

        /// <summary>
        /// 保存word文档
        /// </summary>
        public static void SaveWordDoc(word.Document doc)
        {
            doc.Save();
        }

        /// <summary>
        /// 另存为word文档
        /// </summary>
        public static void SaveAsWordDoc(word.Document doc, string docname)
        {
            object name = docname;
            //save as to
            doc.SaveAs2(ref name, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
                ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
                ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
                ref MissingValue, ref MissingValue);
        }
    }
}
